<template>
  <div class="main-box">
    <TreeFilter
      label="name"
      title="组织机构列表"
      :data="treeFilterData"
      :default-value="initParam.organizationId"
      :show-search="false"
      @change="changeTreeFilter"
    />
    <div class="table-box">
      <ProTable
        ref="proTable"
        title="门店列表"
        :columns="columns"
        :request-api="getStoreOrganizationList"
        :init-param="initParam"
        :request-auto="false"
      >
        <!-- 表格 header 按钮 -->
        <template #tableHeader>
          <el-button
            type="primary"
            v-auth="'set'"
            :icon="CirclePlus"
            @click="openSelectTable('关联门店')"
            :disabled="initParam.organizationId === 0"
          >
            关联门店
          </el-button>
          <el-button v-auth="'add'" type="primary" :icon="CirclePlus" @click="openGroupingDialog('组织机构')">
            新建组织机构
          </el-button>
          <el-button v-auth="'edit'" type="primary" :icon="Setting" plain @click="openEditableDialog('管理组织机构')">
            管理组织机构
          </el-button>
        </template>
        <!-- 表格操作 -->
        <template #operation="scope">
          <el-button v-auth="'delete'" type="primary" link :icon="Delete" @click="deleteAccount(scope.row)"> 删除 </el-button>
        </template>
      </ProTable>
      <SelectTable @selected-list="handleSelected" ref="selectTableRef" />
      <GroupingDialog @handle-up-tree="onUptree" ref="groupingDialogRef" />
      <EditableDialog @up-tree="onUptree" ref="editableDialogRef" />
    </div>
  </div>
</template>
<script setup lang="ts" name="useTreeFilter">
import { ref, reactive, onMounted } from "vue";
import { Operation } from "@/api/interface";
import { useHandleData } from "@/hooks/useHandleData";
import ProTable from "@/components/ProTable/index.vue";
import TreeFilter from "@/components/TreeFilter/index.vue";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import { CirclePlus, Delete, Setting } from "@element-plus/icons-vue";
import GroupingDialog from "@/views/goods/components/GroupingDialog.vue";
import EditableDialog from "@/views/goods/components/EditableDialog.vue";
import SelectTable from "@/components/SelectTable/index.vue";
import {
  getOrganizationList,
  getStoreOrganizationList,
  getNotJoinedStoreList,
  batchCreateStore,
  createOrganization,
  editOrganization,
  deleteOrganization,
  deleteStoreorganization
} from "@/api/modules/operation";

// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTable = ref<ProTableInstance>();

// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({ organizationId: 0 });

// 树形筛选切换
const changeTreeFilter = (val: number) => {
  proTable.value!.pageable.pageNum = 1;
  initParam.organizationId = val;
};

const treeFilterData = ref<any>([]);
const getTreeFilter = async () => {
  const { data } = await getOrganizationList();
  treeFilterData.value = data.list;
  initParam.organizationId = treeFilterData.value[0].id;
};

// 表格配置项
const columns: ColumnProps<Operation.ResOrganizationList>[] = [
  { type: "index", label: "序号", width: 80 },
  { prop: "storeName", sortable: true, label: "门店名称", minWidth: 120, align: "left", search: { el: "input" } },
  { prop: "linkMan", sortable: true, label: "门店联系人", minWidth: 120, align: "left" },
  { prop: "mobile", sortable: true, label: "门店电话", minWidth: 120, align: "left" },
  { prop: "operation", label: "操作", width: 100, fixed: "right" }
];

// 删除用户信息
const deleteAccount = async (params: Operation.ResStoreList) => {
  await useHandleData(deleteStoreorganization, { id: params.id }, `删除【${params.storeName}】门店`);
  proTable.value?.getTableList();
};

const selectTableRef = ref<InstanceType<typeof SelectTable> | null>(null);
const openSelectTable = (title: string) => {
  const params = {
    title,
    isView: false,
    tagsName: "storeName",
    selType: "selection",
    selTags: [],
    columns: [
      { type: "selection", width: 80 },
      {
        prop: "storeName",
        label: "门店名称",
        align: "left",
        search: { el: "input", span: 2, tooltip: "请输入门店名称" }
      }
    ],
    initParam: initParam,
    api: getNotJoinedStoreList,
    getTableList: proTable.value?.getTableList
  };
  selectTableRef.value?.acceptParams(params);
};

const groupingDialogRef = ref<InstanceType<typeof GroupingDialog> | null>(null);
const openGroupingDialog = (title: string, row: Partial<Operation.ResOrganizationList> = {}) => {
  const params = {
    title,
    row: { ...row },
    isView: false,
    api: createOrganization
  };
  groupingDialogRef.value?.acceptParams(params);
};

const editableDialogRef = ref<InstanceType<typeof EditableDialog> | null>(null);
const openEditableDialog = (title: string) => {
  const params = {
    title,
    isView: false,
    row: {},
    api: getOrganizationList,
    edgapi: editOrganization,
    delapi: deleteOrganization
  };
  editableDialogRef.value?.acceptParams(params);
};
const handleSelected = (obj: any) => {
  const ids = obj.list.map(im => im.id);
  batchCreateStore({ id: ids, data: initParam.organizationId })
    .then(() => {
      // initParam.organizationId = initParam.organizationId;
      proTable.value?.getTableList();
    })
    .catch(() => {
      console.log("添加关联门店失败");
    });
};

const onUptree = () => {
  getTreeFilter();
};
onMounted(() => {
  getTreeFilter();
});
</script>
